package com.gaohe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohe.common.R;
import com.gaohe.common.S;
import com.gaohe.pojo.Room;
import com.gaohe.service.RoomService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/room")
public class RoomController {
    @Autowired
    private RoomService roomService;

    /**
     * 分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Room> roomPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Room> qw = new LambdaQueryWrapper<>();
        qw.like(ObjectUtils.isNotEmpty(name), Room::getName, name);
        qw.orderByDesc(Room::getUpdateTime);
        roomService.page(roomPage, qw);
        return R.success(roomPage);
    }

    /**
     * 新增
     * @param room
     * @return
     */
    @PostMapping
    public R insert(@RequestBody Room room) {
        return roomService.save(room)? R.success(S.INSERT_SUCCESS) : R.error(S.INSERT_ERROR);
    }

    /**
     * 修改
     * @param room
     * @return
     */
    @PutMapping
    public R update(@RequestBody Room room){
        return roomService.updateById(room) ? R.success(S.UPDATE_SUCCESS):R.error(S.UPDATE_ERROR);
    }

    /**
     * 根据 id 查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id){
        return R.success(roomService.getById(id));
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping
    public R deleteById(Long id){
        return roomService.removeById(id)? R.success(S.DELETE_SUCCESS):R.error(S.DELETE_ERROR);
    }

    /**
     * 查询全部教室名字
     * @return
     */
    @GetMapping
    public R getAll(){
        LambdaQueryWrapper<Room> qw = new LambdaQueryWrapper<>();
        qw.select(Room::getName);
        return R.success(roomService.list(qw));
    }
}
